'use strict';

const fs = require('fs');
const pump = require('mz-modules/pump');

const BaseController = require('./base.js');

class GoodsController extends BaseController {
  
    async index() {
 
        let goodsResult = await this.ctx.model.Goods.find({});
        
        await this.ctx.render('admin/goods/index', {
            list: goodsResult
        });
    }

    // 添加商品页面
    async add() {
        // 获取所有的颜色
        var colorResult = await this.ctx.model.GoodsColor.find({});

        // 获取所有商品类型
        var goodsType = await this.ctx.model.GoodsType.find({});

        // 获取商品分类
        let goodsCate = await this.ctx.model.GoodsCate.aggregate([
            {
                $lookup:{
                    from: 'goods_cate',          // 关联表 
                    localField: '_id',           // 本表 _id
                    foreignField: 'pid',         // 被关联表 对应的 id
                    as: 'items'
                }
            },
            {
                $match: {
                    "pid" : "0"
                }
            }
        ])

        await this.ctx.render('admin/goods/add',{
            colorResult,
            goodsType,
            goodsCate
        })
    }

    // 获取商品类型的属性
    async goodsTypeAttribute() {
        var cate_id = this.ctx.request.query.cate_id;

        var goodsTypeAttribute = await this.ctx.model.GoodsTypeAttribute.find({cate_id})

        this.ctx.body= {
            result: goodsTypeAttribute
        }
    }

    // 添加商品
    async doAdd() {
        // 获取上传的内容
        let parts = this.ctx.multipart({autoFields: true});
        let files = {};
        let stream;
        while ((stream = await parts()) != null ) {
            if (!stream.filename) {
                break;
            }
            let fieldname = stream.fieldname;   // file表单的 名字 face  

            let dir = await this.service.tools.getUploadFile(stream.filename);   // 返回上传路径地址与数据库保存地址
            let target = dir.uploadDir;
            let writeStream = fs.createWriteStream(target);

            await pump(stream, writeStream);  // 写入并销毁当前流  egg-demo方法

            files = Object.assign(files, {
                [fieldname]: dir.saveDir
            })
        }

        var formFields = Object.assign(files,parts.field);
        console.log(formFields);

        // 增加商品信息
        let goodsRes = new this.ctx.model.Goods(formFields);
        var result = await goodsRes.save();
     
        // 增加图库信息
        var goods_image_list = formFields.goods_image_list;
        if (result._id && goods_image_list) {
            for (var i=0; i<goods_image_list.length; i++) {
                let goodsImageRes = new this.ctx.model.GoodsImage({
                    goods_id: result._id,
                    img_url: goods_image_list[i]
                });
                await goodsImageRes.save();
            }
        }

        // 增加商品类型数据
        var attr_value_list = formFields.attr_value_list;
        var attr_id_list = formFields.attr_id_list;

        console.log(attr_id_list)
        if (result._id && attr_id_list && attr_value_list) {

            for (var i=0; i<attr_value_list.length; i++) {
                if (attr_value_list[i]) {
                    var goodsTypeAttributeResult = await this.ctx.model.GoodsTypeAttribute.find({"_id": attr_id_list[i]});

                    let goodsAttrRes = new this.ctx.model.GoodsAttr({
                        goods_id: result._id,
                        cate_id: formFields.cate_id,
                        attribute_id: attr_id_list[i],
                        attribute_type: goodsTypeAttributeResult[0].attr_type,
                        attribute_title: goodsTypeAttributeResult[0].title,
                        attribute_value: attr_value_list[i]
                    });
                    await goodsAttrRes.save();
                }
            }
        }

        // let focus = new this.ctx.model.Focus(Object.assign(files, parts.field));
        // let result = await focus.save();

        await this.success('/admin/goods', '增加商品数据成功');

    }

    // 编辑商品页面
    async edit() {

        // 获取修改数据的id
        var id = this.ctx.request.query.id;

        // 获取所有的颜色
        var colorResult = await this.ctx.model.GoodsColor.find({});

        // 获取所有商品类型
        var goodsType = await this.ctx.model.GoodsType.find({});

        // 获取商品分类
        let goodsCate = await this.ctx.model.GoodsCate.aggregate([
            {
                $lookup:{
                    from: 'goods_cate',          // 关联表 
                    localField: '_id',           // 本表 _id
                    foreignField: 'pid',         // 被关联表 对应的 id
                    as: 'items'
                }
            },
            {
                $match: {
                    "pid" : "0"
                }
            }
        ])

        // 修改的商品
        var goodsResult = await this.ctx.model.Goods.find({"_id": id});

        console.log(goodsResult);

        // 获取规格信息
        var goodsAttrResult = await this.ctx.model.GoodsAttr.find({"goods_id": goodsResult[0]._id});

        // 商品图库信息
        var goodsImageResult = await this.ctx.model.GoodsImage.find({"goods_id": goodsResult[0]._id});

        await this.ctx.render('admin/goods/edit',{
            colorResult,
            goodsType,
            goodsCate,
            goods: goodsResult[0],
            goodsAttr: goodsAttrResult,
            goodsImage: goodsImageResult
        })
    }

    // 编辑商品提交
    async doEdit() {
        var _id = this.ctx.request.body._id;
        var title = this.ctx.request.body.title;
        var description = this.ctx.request.body.description;
        
        await this.ctx.model.GoodsType.updateOne({"_id":_id}, {title, description})
        await this.success('/admin/goodsType', '编辑商品成功');
    }

    // 富文本编辑器上传图片
    async goodsUploadImage() {
        // 获取上传的内容
        let parts = this.ctx.multipart({autoFields: true});
        let files = {};
        let stream;
        while ((stream = await parts()) != null ) {
            if (!stream.filename) {
                break;
            }
            let fieldname = stream.fieldname;   // file表单的 名字 face  

            let dir = await this.service.tools.getUploadFile(stream.filename);   // 返回上传路径地址与数据库保存地址
            let target = dir.uploadDir;
            let writeStream = fs.createWriteStream(target);

            await pump(stream, writeStream);  // 写入并销毁当前流  egg-demo方法

            files = Object.assign(files, {
                [fieldname]: dir.saveDir
            })
        }

        // 返回格式  {link: 'path/to/image.jpg'}

        this.ctx.body = { link: files.file }
    }

    // 上传相册图片
    async goodsUploadPhoto() {
        // 获取上传的内容
        let parts = this.ctx.multipart({autoFields: true});
        let files = {};
        let stream;
        while ((stream = await parts()) != null ) {
            if (!stream.filename) {
                break;
            }
            let fieldname = stream.fieldname;   // file表单的 名字 face  

            let dir = await this.service.tools.getUploadFile(stream.filename);   // 返回上传路径地址与数据库保存地址
            let target = dir.uploadDir;
            let writeStream = fs.createWriteStream(target);

            await pump(stream, writeStream);  // 写入并销毁当前流  egg-demo方法

            files = Object.assign(files, {
                [fieldname]: dir.saveDir
            })

            // 上传图片成功以后  生成缩略图
            await this.service.tools.jimpImg(target);
        }

        // 返回格式  {link: 'path/to/image.jpg'}
        this.ctx.body = { link: files.file }
    }
}

module.exports = GoodsController;
